<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2021/11/11
 */

namespace App\Http\Requests;

use App\Models\Menu;
use App\Models\MenuPermission;
use App\Models\InfoCategory;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rule;

/**
 * 角色模块表单验证
 * Class RoleRequest
 * @package App\Http\Requests
 */
class RoleRequest extends BaseRequest
{

    /**
     * 注入表单请求验证时自动校验
     *
     * @var bool
     */
    public $autoValidate = false;

    /**
     * 用户是否有权操作，true是，false否
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 字段验证规则
     *
     * @return array
     */
    public function rules()
    {
        $role = $this->role;
        return [
            'id' => 'required|integer',
            'created_user_id' => 'required|integer',
            'name' => ['required', 'min:2', 'max:30', Rule::unique('role')->ignore($role)->where(function ($query) {
                return $query->where('deleted_at', null);
            })],
            'menu_permission_ids' => [
                'nullable',
                function ($attribute, $value, $fail) {
                    $this->validataMenuPermision($attribute, $value, $fail);
                }
            ],
            'category_ids' => [
                'nullable',
                function ($attribute, $value, $fail) {
                    $this->validateCate($attribute, $value, $fail);
                }
            ],
            'description' => 'nullable|max:200',
            'sort' => 'required|integer',
            'status' => 'required|boolean',
            'sort.*.id' => 'required|integer',
            'sort.*.sort' => 'required|integer',
        ];
    }

    /**
     * 提示信息
     * @return array
     */
    public function messages()
    {
        return [
        ];
    }

    /**
     * 定义场景
     * @var \string[][]
     */
    public $scenes = [
        'store' => ['created_user_id', 'name', 'menu_permission_ids', 'category_ids', 'description', 'status'],
        'update' => ['name', 'menu_permission_ids', 'category_ids', 'description', 'status'],
        'destroy' => ['id'],
        'updateStatus' => ['status'],
        'updateSort' => ['sort.*.id', 'sort.*.sort']
    ];

    /**
     * 验证错误的自定义属性
     *
     * @return array
     */
    public function attributes()
    {
        return [
            'id' => __('common.id'),
            'name' => __('role.name'),
            'status' => __('common.status'),
            'description' => __('role.description'),
            'menu_permission_ids' => __('role.menu_permission_ids'),
            'category_ids' => __('role.category_ids'),
            'sort.*.id' => __('common.id'),
            'sort.*.sort' => __('common.sort'),
        ];
    }

    /**
     * 验证前
     *
     * @return void
     */
    protected function prepareForValidation()
    {
        $this->offsetSet('created_user_id', Auth::id());
        if (!isset($this->menu_permission_ids) || empty($this->menu_permission_ids)) $this->offsetSet('menu_permission_ids', []);
        if (!isset($this->category_ids) || empty($this->category_ids)) $this->offsetSet('category_ids', []);
    }

    /**
     * 验证菜单权限
     * @param $attribute
     * @param $value
     * @param $fail
     */
    private function validataMenuPermision($attribute, $value, &$fail)
    {
        if (!empty($value)) {
            $menu = Menu::select('id', 'type')->get()->keyBy('id');
            $getMenuPermission = MenuPermission::select('menu_id', 'permission_id')->get();
            $permission = [];
            collect($getMenuPermission)->each(function ($item) use (&$permission) {
                $permission[$item['menu_id']][] = $item['permission_id'];
            });
            foreach ($value as $item) {
                // 菜单验证
                if (!isset($item['menu_id']) || !isset($menu[$item['menu_id']])) {
                    $fail(__('role.error_exist_menu'));
                    break;
                }
                // 权限验证
                $getMenu = $menu[$item['menu_id']];
                if ($getMenu['type'] == 3 && isset($item['permission_ids']) && !empty($item['permission_ids'])) {
                    print_r($getMenu);
                    $fail(__('role.error_permission_params'));
                    break;
                }
                $is_error_permission = 0;
                if ($getMenu['type'] == 2 && isset($item['permission_ids']) && !empty($item['permission_ids'])) {
                    foreach ($item['permission_ids'] as $pvalue) {
                        if (!in_array($pvalue, $permission[$item['menu_id']])) {
                            $is_error_permission = 1;
                            break;
                        }
                    }
                }
                if ($is_error_permission) {
                    $fail(__('role.error_exist_permission'));
                    break;
                }
            }
        }
    }

    /**
     * 验证栏目
     * @param $attribute
     * @param $value
     * @param $fail
     */
    private function validateCate($attribute, $value, &$fail)
    {
        if (!empty($value)) {
            $cateIds = InfoCategory::pluck('id')->toArray();
            foreach ($value as $category_id) {
                if (!in_array($category_id, $cateIds)) {
                    $fail(__('role.error_exist_category'));
                    break;
                }
            }
        }
    }
}
